package com.yt.user.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.utils.StrUtils;
import com.yt.sys.models.service.ISysUserRoleService;
import com.yt.sys.models.vo.SysUserRoleVO;
import com.yt.user.models.bo.SysUserBO;
import com.yt.user.models.vo.SysUserVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.user.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.user.mapper.SysUserMapper;
import com.yt.user.models.service.ISysUserService;
import com.yt.user.models.bo.SysUserSaveBO;
import com.yt.user.models.dto.SysUserDTO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息控制器
 *
 * @author zhao
 * @Date 2025-09-03 16:21:14
 */
@DubboService
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDTO> implements ISysUserService{

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private ISysUserRoleService sysUserRoleService;

    @Override
    public boolean add(SysUserSaveBO saveBO) {
        SysUserDTO dto = new SysUserDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }



    @Override
    public Page<SysUserVO> selectUserPage(SysUserBO bo) {
        //  构建用户查询条件（支持用户名模糊匹配）
        Page<SysUserDTO> userPage = new Page<>(bo.getPageNo(), bo.getPageSize());
        EntityWrapper<SysUserDTO> userWrapper = new EntityWrapper<>();
        // 用户名模糊匹配
        if (StrUtils.isNotEmpty(bo.getUserName())) {
            userWrapper.like("user_name", bo.getUserName());
        }


        // 添加用户状态过滤
        if (bo.getStatus() != null) {
            userWrapper.eq("status", bo.getStatus());
        }
        // 时间范围过滤
        if (bo.getStartDate() != null) {
            userWrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null) {
            userWrapper.le("create_time", bo.getEndDate());
        }

        // 查询用户分页数据
        userPage = this.selectPage(userPage, userWrapper);

        // 转换为VO并补充角色信息
        List<SysUserVO> userVOList = userPage.getRecords().stream()
                .map(dto -> {
                    SysUserVO vo = new SysUserVO();
                    BeanUtils.copyProperties(dto, vo);
                    // 查询用户关联的角色名称（复用现有接口）
                    List<SysUserRoleVO> roleVOs = sysUserRoleService.selectByUserId(dto.getId());
                    List<String> roleNames = roleVOs.stream()
                            .map(SysUserRoleVO::getRoleName)
                            .collect(Collectors.toList());
                    vo.setRoleNames(roleNames);
                    return vo;
                })
                .collect(Collectors.toList());

        //过滤角色名（如果有角色名查询条件）
        if (StrUtils.isNotEmpty(bo.getRoleName())) {
            String roleNameLike = bo.getRoleName().toLowerCase();
            userVOList = userVOList.stream()
                    .filter(vo -> vo.getRoleNames().stream()
                            .anyMatch(roleName -> roleName.toLowerCase().contains(roleNameLike))
                    )
                    .collect(Collectors.toList());
        }

        // 构建最终分页结果
        Page<SysUserVO> resultPage = new Page<>(bo.getPageNo(), bo.getPageSize());
        resultPage.setTotal(userVOList.size()); // 总条数为过滤后的数据量
        // 处理分页截取
        int start = (bo.getPageNo() - 1) * bo.getPageSize();
        int end = Math.min(start + bo.getPageSize(), userVOList.size());
        resultPage.setRecords(userVOList.subList(start, end));

        return resultPage;
    }
}
